package library.net.retrofit;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import retrofit2.Retrofit;

/**
 * @author Created by qiang.hou on 2018/11/23.
 * @version 1.0
 */
public class ApiFactory {
    private List<Class> serviceClassCache = new ArrayList<>();
    private Map<Class, Object> serviceCache = new ConcurrentHashMap<>();

    private ApiFactory() {
        addService(IBaseApi.class);
    }

    public <T> void addService(Class<T> service) {
        serviceClassCache.add(service);
    }

    public <T> void removeService(Class<T> service) {
        if (serviceClassCache.contains(service)) {
            serviceClassCache.remove(service);
        }
    }

    /**
     * 静态内部类
     */
    private static class SingletonHolder {
        private static final ApiFactory INSTANCE = new ApiFactory();
    }

    public static ApiFactory getInstance() {
        return SingletonHolder.INSTANCE;
    }

    @SuppressWarnings("unchecked")
    public <T> T createApiService(Retrofit retrofit, Class<T> service) {
        for (Class item : serviceClassCache) {
            if (service == item) {
                if (serviceCache.containsKey(service)) {
                    return (T) serviceCache.get(service);
                } else {
                    serviceCache.put(service, retrofit.create(service));
                }
                return (T) serviceCache.get(service);
            }
        }
        return null;
    }
}
